#include "datagenerator.h"
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QSqlRecord>
#include <QVariant>
#include <QDateTime>
#include <QDate>
#include <QStringList>
#include <QRegularExpression>
#include <QRandomGenerator>
#include <QApplication>
#include <QMessageBox>

DataGenerator::DataGenerator(QObject *parent)
    : QObject(parent)
    , m_cancelRequested(false)
{
}

void DataGenerator::setDatabase(const QSqlDatabase &db)
{
    m_database = db;
}

bool DataGenerator::generateData(const TableConfig &config)
{
    m_cancelRequested = false;
    m_lastError.clear();
    
    if (!m_database.isOpen()) {
        m_lastError = tr("Database is not open");
        emit generationError(m_lastError);
        return false;
    }
    
    // 创建表（如果不存在）
    if (!createTable(config)) {
        emit generationError(m_lastError);
        return false;
    }
    
    // 插入数据
    if (!insertData(config)) {
        emit generationError(m_lastError);
        return false;
    }
    
    QString message = tr("Successfully generated %1 rows of data for table '%2'")
                     .arg(config.rowCount).arg(config.name);
    emit generationFinished(message);
    return true;
}

QString DataGenerator::getLastErrorMessage() const
{
    return m_lastError;
}

void DataGenerator::cancelGeneration()
{
    m_cancelRequested = true;
}

QVariant DataGenerator::generateValue(const ColumnConfig &config)
{
    // 检查是否应该生成NULL值
    if (config.nullable && m_random.generateDouble() < config.nullProbability) {
        return QVariant();
    }
    
    // 根据数据类型生成相应的值
    QString type = config.type.toUpper();
    
    if (type.contains("CHAR") || type.contains("TEXT")) {
        return generateString(config);
    } else if (type.contains("INT") || type.contains("INTEGER")) {
        return generateInt(config);
    } else if (type.contains("REAL") || type.contains("FLOAT") || type.contains("DOUBLE")) {
        return generateDouble(config);
    } else if (type.contains("DATE") && !type.contains("TIME")) {
        return generateDate(config);
    } else if (type.contains("DATETIME") || type.contains("TIMESTAMP")) {
        return generateDateTime(config);
    } else {
        // 默认生成字符串
        return generateString(config);
    }
}

QString DataGenerator::generateString(const ColumnConfig &config)
{
    static const QString chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
    
    int length = m_random.bounded(config.minLength, config.maxLength + 1);
    QString result;
    
    if (!config.pattern.isEmpty()) {
        // 如果有模式，则根据模式生成
        result = config.pattern;
        // 简单替换，例如将#替换为数字，将@替换为字母
        result.replace("#", QString::number(m_random.bounded(0, 10)));
        result.replace("@", QString(chars.at(m_random.bounded(0, 52))));
    } else {
        // 随机生成字符串
        for (int i = 0; i < length; ++i) {
            result += chars.at(m_random.bounded(0, chars.length()));
        }
    }
    
    return result;
}

int DataGenerator::generateInt(const ColumnConfig &config)
{
    int minVal = config.minValue.isValid() ? config.minValue.toInt() : 0;
    int maxVal = config.maxValue.isValid() ? config.maxValue.toInt() : 10000;
    
    if (minVal >= maxVal) {
        return minVal;
    }
    
    return m_random.bounded(minVal, maxVal + 1);
}

double DataGenerator::generateDouble(const ColumnConfig &config)
{
    double minVal = config.minValue.isValid() ? config.minValue.toDouble() : 0.0;
    double maxVal = config.maxValue.isValid() ? config.maxValue.toDouble() : 10000.0;
    
    if (minVal >= maxVal) {
        return minVal;
    }
    
    return minVal + m_random.generateDouble() * (maxVal - minVal);
}

QVariant DataGenerator::generateDate(const ColumnConfig &config)
{
    QDate minDate = config.minValue.isValid() ? config.minValue.toDate() : QDate::currentDate().addYears(-1);
    QDate maxDate = config.maxValue.isValid() ? config.maxValue.toDate() : QDate::currentDate();
    
    if (minDate >= maxDate) {
        return minDate;
    }
    
    int days = minDate.daysTo(maxDate);
    QDate result = minDate.addDays(m_random.bounded(0, days + 1));
    return result;
}

QVariant DataGenerator::generateDateTime(const ColumnConfig &config)
{
    QDateTime minDateTime = config.minValue.isValid() ? config.minValue.toDateTime() : QDateTime::currentDateTime().addYears(-1);
    QDateTime maxDateTime = config.maxValue.isValid() ? config.maxValue.toDateTime() : QDateTime::currentDateTime();
    
    if (minDateTime >= maxDateTime) {
        return minDateTime;
    }
    
    qint64 secs = minDateTime.secsTo(maxDateTime);
    QDateTime result = minDateTime.addSecs(m_random.bounded(0, secs + 1));
    return result;
}

bool DataGenerator::createTable(const TableConfig &config)
{
    // 检查表是否已存在
    if (m_database.tables().contains(config.name)) {
        return true; // 表已存在，无需创建
    }
    
    // 生成CREATE TABLE语句
    QString sql = "CREATE TABLE " + config.name + " (";
    
    QStringList columnDefs;
    for (auto it = config.columns.constBegin(); it != config.columns.constEnd(); ++it) {
        const ColumnConfig &colConfig = it.value();
        QString columnDef = "\"" + colConfig.name + "\" " + colConfig.type;
        
        if (!colConfig.nullable) {
            columnDef += " NOT NULL";
        }
        
        columnDefs.append(columnDef);
    }
    
    sql += columnDefs.join(", ");
    sql += ")";
    
    QSqlQuery query(m_database);
    if (!query.exec(sql)) {
        m_lastError = tr("Failed to create table: %1").arg(query.lastError().text());
        return false;
    }
    
    return true;
}

bool DataGenerator::insertData(const TableConfig &config)
{
    if (config.columns.isEmpty() || config.rowCount <= 0) {
        m_lastError = tr("Invalid table configuration");
        return false;
    }
    
    // 准备INSERT语句
    QString sql = "INSERT INTO " + config.name + " (";
    
    QStringList columnNames;
    for (auto it = config.columns.constBegin(); it != config.columns.constEnd(); ++it) {
        columnNames.append("\"" + it.key() + "\"");
    }
    
    sql += columnNames.join(", ");
    sql += ") VALUES (";
    
    QStringList placeholders;
    for (int i = 0; i < config.columns.size(); ++i) {
        placeholders.append("?");
    }
    
    sql += placeholders.join(", ");
    sql += ")";
    
    QSqlQuery query(m_database);
    query.prepare(sql);
    
    // 插入数据
    for (int i = 0; i < config.rowCount; ++i) {
        if (m_cancelRequested) {
            m_lastError = tr("Generation cancelled by user");
            return false;
        }
        
        query.clear();
        query.prepare(sql);
        
        // 为每一列生成值
        for (auto it = config.columns.constBegin(); it != config.columns.constEnd(); ++it) {
            QVariant value = generateValue(it.value());
            query.addBindValue(value);
        }
        
        if (!query.exec()) {
            m_lastError = tr("Failed to insert data: %1").arg(query.lastError().text());
            return false;
        }
        
        // 发出进度信号（每100行报告一次进度）
        if (i % 100 == 0 || i == config.rowCount - 1) {
            int percentage = (i + 1) * 100 / config.rowCount;
            emit generationProgress(percentage);
            QApplication::processEvents(); // 处理事件队列，保持界面响应
        }
    }
    
    return true;
}